import React from 'react';
import { Upload, UploadProps, Button, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import instance from '../../api';
import eventBus from '../../model/event';
import { UploadFile } from 'antd/lib/upload/interface';

interface ajaxOptions {
    action: string,
    data: any,
    file: UploadFile,
    headers: any,
    method: string
}

export default class MyUpload extends React.Component {
    public state = {
        fileList: [] as UploadFile[],
        projectId: '',
    };

    public projectId = '';

    constructor(props: { projectId: number | undefined }) {
        super(props);
    }

    componentDidUpdate(nextProps: any, nextState: any) {
        if (nextProps.projectId !== this.state.projectId) {
            this.setState({
                projectId: nextProps.projectId
            })
        }
    }

    beforeUpload = (file: File) => {
        if (file.type !== 'image/png') {
            message.error(`${file.name} is not a png file`);
        }
        return file.type === 'image/png' ? true : Upload.LIST_IGNORE;
    }

    handleChange = info => {
        let fileList = [...info.fileList];

        fileList = fileList.map(file => {
            if (file.response) {
                // Component will show file.url as link
                file.url = file.response.url;
            }
            return file;
        });

        this.setState({ fileList });
    };

    handleUpload = (options: ajaxOptions) => {
        const { file } = options;

        const fr = new FileReader();

        fr.readAsArrayBuffer(file);

        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;

        xhr.addEventListener("readystatechange", () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    message.success('上传成功！');
                    const fileList = [...this.state.fileList];
                    const index = fileList.findIndex((fq: UploadFile) => fq.uid === file.uid);
                    if (index >= 0) {
                        fileList[index].status = 'success';
                        this.setState({
                            fileList: fileList
                        });
                        eventBus.emit('bundle_refresh');
                    }
                } else {
                    const fileList = [...this.state.fileList];
                    const index = fileList.findIndex((fq: UploadFile) => fq.uid === file.uid);
                    if (index >= 0) {
                        fileList[index].status = 'error';
                        this.setState({
                            fileList: fileList
                        });
                    }
                    message.warning('上传失败!');
                }
            }
        });

        xhr.open("POST", `${instance.defaults.baseURL}/bundle?projectId=${this.state.projectId}&name=${file.name}`);

        fr.onload = function (event: any) {
            // console.log(file, event.target.result);
            xhr.send(event.target.result);
        }

    }

    render() {
        const props = {
            onChange: this.handleChange,
            multiple: false,
            withCredentials: true,
            customRequest: this.handleUpload
        };

        return (
            <Upload {...props} fileList={this.state.fileList}>
                <Button icon={<UploadOutlined />}>Upload</Button>
            </Upload>
        );
    }
}